import { z } from "zod";
import { createTRPCRouter, publicProcedure, protectedProcedure } from "~/server/api/trpc";
import { TRPCError } from "@trpc/server";
// 计算课程进度的辅助函数
const calculateCourseProgress = (tasks: any[]) => {
  let totalSteps = 0;
  let completedSteps = 0;
  
  tasks.forEach(task => {
    task.steps.forEach((step: any) => {
      totalSteps++;
      if (step.completions.length > 0) {
        completedSteps++;
      }
    });
  });
  
  return {
    totalSteps,
    completedSteps,
    progressPercentage: totalSteps > 0 
      ? Math.round((completedSteps / totalSteps) * 100) 
      : 0
  };
};

export const courseRouter = createTRPCRouter({
  getEnrolledCourses: protectedProcedure
    .query(async ({ ctx }) => {
      if (!ctx.session?.user?.id) {
        throw new TRPCError({
          code: "UNAUTHORIZED",
          message: "请先登录",
        });
      }

      try {
        const enrollments = await ctx.db.enrollment.findMany({
          where: { 
            studentId: ctx.session.user.id
          },
          include: {
            course: {
              include: {
                teacher: {
                  select: {
                    name: true
                  }
                },
                tasks: {
                  include: {
                    steps: {
                      include: {
                        completions: {
                          where: {
                            userId: ctx.session.user.id
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          orderBy: { enrolledAt: 'desc' }
        });

        return await Promise.all(enrollments.map(async (enrollment) => {
          // 计算课程完成进度
          const { progressPercentage } = calculateCourseProgress(enrollment.course.tasks);
          
          // 更新enrollment的progress字段
          await ctx.db.enrollment.update({
            where: { id: enrollment.id },
            data: { 
              progress: progressPercentage,
              status: progressPercentage === 100 ? "COMPLETED" : "ENROLLED"
            }
          });

          return {
            id: enrollment.course.id,
            title: enrollment.course.title,
            description: enrollment.course.description,
            status: progressPercentage === 100 ? "COMPLETED" : "ENROLLED",
            progressPercentage: progressPercentage,
            teacher: enrollment.course.teacher
          };
        }));
      } catch (error) {
        if (error instanceof TRPCError) throw error;
        throw new TRPCError({
          code: "INTERNAL_SERVER_ERROR",
          message: "获取课程列表失败",
          cause: error,
        });
      }
    }),

  getTasks: protectedProcedure
    .input(z.object({ courseId: z.string() }))
    .query(async ({ ctx, input }) => {
      if (!ctx.session?.user?.id) {
        throw new TRPCError({
          code: "UNAUTHORIZED",
          message: "请先登录",
        });
      }

      try {
        // 验证用户是否已加入该课程
        const enrollment = await ctx.db.enrollment.findFirst({
          where: {
            courseId: input.courseId,
            studentId: ctx.session.user.id,
            status: 'ENROLLED'
          }
        });

        if (!enrollment) {
          throw new TRPCError({
            code: "FORBIDDEN",
            message: "您还未加入该课程",
          });
        }

        return await ctx.db.task.findMany({
          where: { courseId: input.courseId },
          include: { subtasks: true },
          orderBy: { order: 'asc' }
        }) as Task[];
      } catch (error) {
        if (error instanceof TRPCError) throw error;
        throw new TRPCError({
          code: "INTERNAL_SERVER_ERROR",
          message: "获取任务列表失败",
          cause: error,
        });
      }
    }),
    
  getTaskContent: protectedProcedure
    .input(z.object({ 
      courseId: z.string(),
      taskId: z.string().optional()
    }))
    .query(async ({ ctx, input }) => {
      if (!ctx.session?.user?.id) {
        throw new TRPCError({
          code: "UNAUTHORIZED",
          message: "请先登录",
        });
      }

      try {
        // 验证用户是否已加入该课程
        const enrollment = await ctx.db.enrollment.findFirst({
          where: {
            courseId: input.courseId,
            studentId: ctx.session.user.id,
            status: 'ENROLLED'
          }
        });

        if (!enrollment) {
          throw new TRPCError({
            code: "FORBIDDEN",
            message: "您还未加入该课程",
          });
        }

        if (!input.taskId) return null;
        
        return await ctx.db.task.findFirst({
          where: { 
            id: input.taskId,
            courseId: input.courseId
          },
          select: {
            id: true,
            title: true,
            content: true
          }
        });
      } catch (error) {
        if (error instanceof TRPCError) throw error;
        throw new TRPCError({
          code: "INTERNAL_SERVER_ERROR",
          message: "获取任务内容失败",
          cause: error,
        });
      }
    }),
    // 获取学生所有的课程
  getAllCourses: protectedProcedure
    .query(async ({ ctx }) => {
      if (!ctx.session?.user?.id) {
        throw new TRPCError({
          code: "UNAUTHORIZED",
          message: "请先登录",
        });
      }

      try {
        const enrollments = await ctx.db.enrollment.findMany({
          where: { 
            studentId: ctx.session.user.id
          },
          include: {
            course: {
              include: {
                teacher: {
                  select: {
                    name: true
                  }
                },
                tasks: {
                  include: {
                    steps: {
                      include: {
                        completions: {
                          where: {
                            userId: ctx.session.user.id
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          orderBy: { enrolledAt: 'desc' }
        });

        return await Promise.all(enrollments.map(async (enrollment) => {
          // 计算课程完成进度
          const { progressPercentage } = calculateCourseProgress(enrollment.course.tasks);
          
          // 更新enrollment的progress字段
          await ctx.db.enrollment.update({
            where: { id: enrollment.id },
            data: { 
              progress: progressPercentage,
              status: progressPercentage === 100 ? "COMPLETED" : "ENROLLED"
            }
          });

          return {
            id: enrollment.course.id,
            title: enrollment.course.title,
            description: enrollment.course.description,
            status: progressPercentage === 100 ? "COMPLETED" : "ENROLLED",
            progressPercentage: progressPercentage,
            teacher: enrollment.course.teacher
          };
        }));
      } catch (error) {
        if (error instanceof TRPCError) throw error;
        throw new TRPCError({
          code: "INTERNAL_SERVER_ERROR",
          message: "获取课程列表失败",
          cause: error,
        });
      }
    })
});